package com.hmall.order.listener;

import com.hmall.common.feign.ItemClient;
import com.hmall.common.feign.UserClient;
import com.hmall.common.pojo.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ListenItemService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;

    /**
     * 接收延迟消息-延迟插件
     *
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue"),
            exchange = @Exchange(name = "delay.direct", delayed = "true"),
            key = "delay"
    ))
    public void listenDelayQueue(String msg) {
        log.debug("接收的订单id是：{}", msg);
        long orderId = Long.parseLong(msg);
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            try {
                throw new Exception("没有该订单");
            } catch (Exception e) {
                e.getMessage();
            }
        }
        Integer status = order.getStatus();
        if (status == 1) {
            order.setStatus(5);
            OrderDetail orderDetail = orderDetailMapper.selectById(orderId);
            if (orderDetail != null) {
                Long itemId = orderDetail.getItemId();
                Item item = itemClient.listById(itemId);
                if (item != null) {
                    //还原库存
                    item.setStock(item.getStock() + orderDetail.getNum());
                    itemClient.updateById(item);
                }else {
                    log.info("无item");
                }
            }else {
                log.info("无orderDetail");
            }
        } else if (status == 5) {
            orderMapper.deleteById(orderId);
            orderDetailMapper.deleteById(orderId);
            orderLogisticsMapper.deleteById(orderId);
        }

        /*return;*/
    }
}
